package com.xiaozhengkeji.springboot.frame.easy.api;

import com.alibaba.fastjson.JSON;
import com.xiaozhengkeji.springboot.frame.easy.Bean.QueryInfo;
import com.xiaozhengkeji.springboot.frame.easy.Bean.ResponseBean;
import com.xiaozhengkeji.springboot.frame.easy.Bean.UploadFilePoJo;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysFile;
import com.xiaozhengkeji.springboot.frame.easy.entity.SysUser;
import com.xiaozhengkeji.springboot.frame.easy.security.JwtTokenUtil;
import com.xiaozhengkeji.springboot.frame.easy.service.SysFileService;
import com.xiaozhengkeji.springboot.frame.easy.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/public/file")
public class FileApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private SysUserService sysUserService;


    @GetMapping("/all")
    @PreAuthorize(value = "isAuthenticated()")
    public ResponseBean getUserList(QueryInfo queryInfo,
                                    @RequestHeader String Token) {
        String username = jwtTokenUtil.getUsernameFromToken(Token.substring("Bearer ".length()));
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize(); //页码
        sysUser = sysUserService.queryAll(sysUser).get(0);
        if (sysUser.getUserRole().equalsIgnoreCase("ROLE_admin")) {
            int numbers = sysFileService.queryAll(new SysFile()).size();// 获取数据总数

            return new ResponseBean(numbers, "ok", sysFileService.queryAllByLimit(pageStart, queryInfo.getPageSize()));
        } else {
            SysFile sysFile = new SysFile();
            sysFile.setUuid(sysUser.getUuid());
            List<SysFile> sysFiles = sysFileService.queryAll(sysFile);
            int numbers = sysFiles.size();
            return new ResponseBean(numbers, "ok", sysFiles.subList(pageStart, queryInfo.getPageSize()));
        }
    }

    @PostMapping("/uploadfile")
    public ResponseBean uploadFile(@RequestParam("file") MultipartFile file,
                                   @RequestHeader String Token) throws Exception {

        if (file.isEmpty()) {
            return new ResponseBean(501, "请选择文件", null);
        }
        String fileName = file.getOriginalFilename();
        try {
            UploadFilePoJo uploadFile = new UploadFilePoJo();
            uploadFile.setName(fileName);
            uploadFile.setCreatedTime(new Date());
            uploadFile.setContent(new Binary(file.getBytes()));
            uploadFile.setContentType(file.getContentType());
            uploadFile.setSize(file.getSize());
            UploadFilePoJo savedFile = mongoTemplate.save(uploadFile);
            String url = savedFile.getId();
            SysFile filelist = new SysFile();
            filelist.setFid(url);
            filelist.setUpData(savedFile.getCreatedTime());
            filelist.setFileName(fileName);
            filelist.setSize(savedFile.getSize());
            filelist.setUuid(jwtTokenUtil.getUsernameFromToken(Token.substring("Bearer ".length())));
            log.info(JSON.toJSONString(sysFileService.insert(filelist)));
            return new ResponseBean(200, "上传成功", null);
        } catch (IOException e) {
            return new ResponseBean(500, "上传失败", null);
        }
    }

    @GetMapping("/download")
    public byte[] download(@RequestParam(name = "fid") String fileId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] data = null;
        UploadFilePoJo file = mongoTemplate.findById(fileId, UploadFilePoJo.class);
        if (file != null) {
            data = file.getContent().getData();
        }
        String fileName = file.getName();
        if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        // 通知浏览器进行文件下载
        response.setContentType(file.getContentType());
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        return data;
    }

    @DeleteMapping("/delete")
    @PreAuthorize("hasRole('ROLE_admin')")
    public String delete(@RequestParam(name = "fid") String fileId,
                         @RequestHeader String Token) {
        SysFile sysFile = new SysFile();
        sysFile.setFid(fileId);
        sysFile = sysFileService.queryAll(sysFile).get(0);
        UploadFilePoJo file = mongoTemplate.findById(fileId, UploadFilePoJo.class);
        sysFileService.deleteById(sysFile.getId());
        mongoTemplate.remove(file);
        return "success";
    }
}
